from datetime import datetime, date, time
from typing import Optional
from fastapi import APIRouter, Query
from apps.schemas.schemas import AppointmentCreateRequest, AppointmentUpdateRequest
from apps.services.student_appoinment import (
    get_all_appointments,
    get_appointments_by_user_id,
    get_coach_appointments_by_status,
    get_appointment_by_id,
    create_appointment,
    update_appointment,
    delete_appointment,
    confirm_appointment,
    cancel_appointment
)

appointments = APIRouter()


@appointments.get("/msg")
async def get_all_appointments_api(page: int = Query(1, ge=1), page_size: int = Query(10, ge=1, le=100)):
    """
    获取所有预约列表（分页）
    """
    try:
        total, appointments_data = await get_all_appointments(page, page_size)
        return {
            "status": 200,
            "message": "success",
            "data": appointments_data,
            "total": total
        }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Error retrieving appointments: {str(e)}",
            "data": [],
            "total": 0
        }


@appointments.get("/msg/{user_id}")
async def get_appointments_by_user_id_api(user_id: int):
    """
    根据用户ID获取预约信息（学生或教练）
    """
    try:
        appointments_data = await get_appointments_by_user_id(user_id)
        return {
            "status": 200,
            "message": "success",
            "data": appointments_data
        }
    except ValueError as e:
        return {
            "status": 404,
            "message": str(e),
            "data": []
        }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Error retrieving appointments: {str(e)}",
            "data": []
        }


@appointments.get("/msg/coach/{user_id}")
async def get_coach_appointments_by_status_api(
        user_id: int,
        page: int = Query(1, ge=1, description="页码"),
        page_size: int = Query(10, ge=1, le=100, description="每页数量"),
        status: Optional[str] = Query(None, description="预约状态")
):
    """
    根据教练用户ID和状态筛选预约
    """
    try:
        appointments_data = await get_coach_appointments_by_status(user_id, page, page_size, status)
        return {
            "status": 200,
            "message": "success",
            "data": appointments_data
        }
    except ValueError as e:
        return {
            "status": 404,
            "message": str(e),
            "data": None
        }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Error retrieving coach appointments: {str(e)}",
            "data": None
        }


@appointments.get("/msg/{appointment_id}")
async def get_appointment_api(appointment_id: int):
    """
    根据预约ID获取预约信息
    """
    try:
        appointment_data = await get_appointment_by_id(appointment_id)
        if appointment_data:
            return {
                "status": 200,
                "message": "success",
                "data": appointment_data
            }
        else:
            return {
                "status": 404,
                "message": "Appointment not found",
                "data": {}
            }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Error retrieving appointment: {str(e)}",
            "data": {}
        }


@appointments.post("/add")
async def create_appointment_api(data: AppointmentCreateRequest):
    """
    创建新的预约
    """
    try:
        await create_appointment(data)
        return {
            "status": 201,
            "message": "Appointment created successfully",
            "data": {}
        }
    except ValueError as e:
        return {
            "status": 404,
            "message": str(e),
            "data": {}
        }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Error creating appointment: {str(e)}",
            "data": {}
        }


@appointments.put("/update/{appointment_id}")
async def update_appointment_api(appointment_id: int, data: AppointmentUpdateRequest):
    """
    更新预约信息
    """
    try:
        updated = await update_appointment(appointment_id, data)
        if updated:
            return {
                "status": 200,
                "message": "Appointment updated successfully",
                "data": {}
            }
        else:
            return {
                "status": 404,
                "message": "Appointment not found",
                "data": {}
            }
    except ValueError as e:
        return {
            "status": 404,
            "message": str(e),
            "data": {}
        }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Error updating appointment: {str(e)}",
            "data": {}
        }


@appointments.delete("/delete/{appointment_id}")
async def delete_appointment_api(appointment_id: int):
    """
    删除预约
    """
    try:
        deleted = await delete_appointment(appointment_id)
        if deleted:
            return {
                "status": 200,
                "message": "Appointment deleted successfully",
                "data": {}
            }
        else:
            return {
                "status": 404,
                "message": "Appointment not found",
                "data": {}
            }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Error deleting appointment: {str(e)}",
            "data": {}
        }


@appointments.put("/msg/{appointment_id}/confirm")
async def confirm_appointment_api(appointment_id: int):
    """
    确认预约
    """
    try:
        appointment_data = await confirm_appointment(appointment_id)
        if appointment_data:
            return {
                "status": 200,
                "message": "Appointment confirmed successfully",
                "data": appointment_data
            }
        else:
            return {
                "status": 404,
                "message": "Appointment not found",
                "data": None
            }
    except ValueError as e:
        return {
            "status": 400,
            "message": str(e),
            "data": None
        }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Error confirming appointment: {str(e)}",
            "data": None
        }


@appointments.put("/msg/{appointment_id}/cancel")
async def cancel_appointment_api(appointment_id: int):
    """
    取消预约
    """
    try:
        appointment_data = await cancel_appointment(appointment_id)
        if appointment_data:
            return {
                "status": 200,
                "message": "Appointment cancelled successfully",
                "data": appointment_data
            }
        else:
            return {
                "status": 404,
                "message": "Appointment not found",
                "data": None
            }
    except ValueError as e:
        return {
            "status": 400,
            "message": str(e),
            "data": None
        }
    except Exception as e:
        return {
            "status": 500,
            "message": f"Error cancelling appointment: {str(e)}",
            "data": None
        }
